package name.vaccari.matteo.tai.chat.servlet;
import java.io.PrintWriter;

import name.vaccari.matteo.tai.chat.domain.Message;
import name.vaccari.matteo.tai.chat.domain.MessageRepository;
import name.vaccari.matteo.tai.chat.views.ChatView;


public class ChatController {

	private MessageRepository messageRepository;
	private ChatView chatView;
	private static final int MAX_MESSAGES = 5;
	
	public ChatController(MessageRepository repository, ChatView chatView) {
		this.messageRepository = repository;
		this.chatView = chatView;
	}

	public void service(String method, Message message, PrintWriter writer) {
		if(method.equals("POST")) {
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
			}
			messageRepository.save(message);
		}
		chatView.setMessages(messageRepository.getLatestMessages(MAX_MESSAGES));
		writer.print(chatView.toString());
		writer.flush();
	}
}
